/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.beans.factory.xml;

import java.util.HashMap;
import java.util.Map;

import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.lang.Nullable;

/**
 * Support class for implementing custom {@link NamespaceHandler NamespaceHandlers}.
 * Parsing and decorating of individual {@link Node Nodes} is done via {@link BeanDefinitionParser}
 * and {@link BeanDefinitionDecorator} strategy interfaces, respectively.
 *
 * <p>Provides the {@link #registerBeanDefinitionParser} and {@link #registerBeanDefinitionDecorator}
 * methods for registering a {@link BeanDefinitionParser} or {@link BeanDefinitionDecorator}
 * to handle a specific element.
 *
 * @author Rob Harrop
 * @author Juergen Hoeller
 * @since 2.0
 * @see #registerBeanDefinitionParser(String, BeanDefinitionParser)
 * @see #registerBeanDefinitionDecorator(String, BeanDefinitionDecorator)
 */
public abstract class NamespaceHandlerSupport implements NamespaceHandler {

	/**
	 * Stores the {@link BeanDefinitionParser} implementations keyed by the
	 * local name of the {@link Element Elements} they handle.
	 */
	private final Map<String, BeanDefinitionParser> parsers = new HashMap<>();

	/**
	 * Stores the {@link BeanDefinitionDecorator} implementations keyed by the
	 * local name of the {@link Element Elements} they handle.
	 */
	private final Map<String, BeanDefinitionDecorator> decorators = new HashMap<>();

	/**
	 * Stores the {@link BeanDefinitionDecorator} implementations keyed by the local
	 * name of the {@link Attr Attrs} they handle.
	 */
	private final Map<String, BeanDefinitionDecorator> attributeDecorators = new HashMap<>();


	/**
	 * 解析提供的 {@link Element} 元素，通过委托给已为该 {@link Element} 注册的 {@link BeanDefinitionParser} 来执行解析操作。
	 *
	 * 该方法的核心功能是根据传入的 XML 元素，找到相应的解析器（{@link BeanDefinitionParser}），
	 * 并将解析任务交给该解析器来处理。解析器会根据 XML 元素的类型，将其转换为 Spring 中相应的 Bean 定义。
	 *
	 * 例如，在解析 Spring 配置文件时，当遇到不同类型的标签时，会根据标签的命名空间或标签名选择合适的 {@link BeanDefinitionParser}。
	 * 然后，解析器会处理该标签，并返回解析后的 {@link BeanDefinition}，这些定义会被 Spring 容器用来创建相应的 Bean。
	 *
	 * <p>典型使用场景包括：
	 * <ul>
	 *     <li>解析自定义命名空间（如 <code>&lt;tx:annotation-driven&gt;</code>、<code>&lt;context:component-scan&gt;</code>）；
	 *     <li>处理特定业务框架自定义标签（如 Dubbo 或 MyBatis 的 XML 标签）；
	 *     <li>将 XML 中的属性、子元素映射为 Bean 属性、构造参数或内部 Bean 定义。</li>
	 * </ul>
	 *
	 * Parses the supplied {@link Element} by delegating to the {@link BeanDefinitionParser} that is
	 * registered for that {@link Element}.
	 *
	 * @param element the XML 元素需要解析的 {@link Element} 对象
	 * @param parserContext the {@link ParserContext} 用于解析上下文的信息（例如当前环境、父级定义等）
	 * @return 解析后的 {@link BeanDefinition} 对象，如果没有找到对应的解析器则返回 {@code null}
	 */
	@Override
	@Nullable
	public BeanDefinition parse(Element element, ParserContext parserContext) {
		// 根据元素和解析上下文，查找对应的 BeanDefinitionParser
		BeanDefinitionParser parser = findParserForElement(element, parserContext);

		// 如果找到了对应的解析器，则调用解析器的 parse 方法进行解析；否则返回 null
		return (parser != null ? parser.parse(element, parserContext) : null);
	}


	/**
	 * 从注册的实现中，根据提供的 {@link Element} 元素的本地名称，查找对应的 {@link BeanDefinitionParser}。
	 * 该方法根据传入的 XML 元素的本地名称（去除命名空间部分），在已注册的解析器中查找相应的 {@link BeanDefinitionParser}。
	 * 本地名称是 XML 元素标签的名称，通常用于标识该标签的类型。在 Spring 中，每种类型的 XML 元素（如 `<bean>`、`<property>`）都有一个对应的解析器。
	 * 如果找不到对应的解析器，方法会抛出一个致命的错误，表示无法解析该元素。
	 *
	 * Locates the {@link BeanDefinitionParser} from the register implementations using
	 * the local name of the supplied {@link Element}.
	 */
	@Nullable
	private BeanDefinitionParser findParserForElement(Element element, ParserContext parserContext) {
		// 获取当前 XML 元素的本地名称，即不包含命名空间的部分
		String localName = parserContext.getDelegate().getLocalName(element);
		// 根据本地名称查找对应的解析器
		BeanDefinitionParser parser = this.parsers.get(localName);
		// 如果没有找到对应的解析器，抛出致命错误
		if (parser == null) {
			parserContext.getReaderContext().fatal(
					"Cannot locate BeanDefinitionParser for element [" + localName + "]", element);
		}
		// 返回找到的解析器
		return parser;
	}

	/**
	 * Decorates the supplied {@link Node} by delegating to the {@link BeanDefinitionDecorator} that
	 * is registered to handle that {@link Node}.
	 */
	@Override
	@Nullable
	public BeanDefinitionHolder decorate(
			Node node, BeanDefinitionHolder definition, ParserContext parserContext) {

		BeanDefinitionDecorator decorator = findDecoratorForNode(node, parserContext);
		return (decorator != null ? decorator.decorate(node, definition, parserContext) : null);
	}

	/**
	 * Locates the {@link BeanDefinitionParser} from the register implementations using
	 * the local name of the supplied {@link Node}. Supports both {@link Element Elements}
	 * and {@link Attr Attrs}.
	 */
	@Nullable
	private BeanDefinitionDecorator findDecoratorForNode(Node node, ParserContext parserContext) {
		BeanDefinitionDecorator decorator = null;
		String localName = parserContext.getDelegate().getLocalName(node);
		if (node instanceof Element) {
			decorator = this.decorators.get(localName);
		}
		else if (node instanceof Attr) {
			decorator = this.attributeDecorators.get(localName);
		}
		else {
			parserContext.getReaderContext().fatal(
					"Cannot decorate based on Nodes of type [" + node.getClass().getName() + "]", node);
		}
		if (decorator == null) {
			parserContext.getReaderContext().fatal("Cannot locate BeanDefinitionDecorator for " +
					(node instanceof Element ? "element" : "attribute") + " [" + localName + "]", node);
		}
		return decorator;
	}


	/**
	 * Subclasses can call this to register the supplied {@link BeanDefinitionParser} to
	 * handle the specified element. The element name is the local (non-namespace qualified)
	 * name.
	 */
	protected final void registerBeanDefinitionParser(String elementName, BeanDefinitionParser parser) {
		this.parsers.put(elementName, parser);
	}

	/**
	 * Subclasses can call this to register the supplied {@link BeanDefinitionDecorator} to
	 * handle the specified element. The element name is the local (non-namespace qualified)
	 * name.
	 */
	protected final void registerBeanDefinitionDecorator(String elementName, BeanDefinitionDecorator dec) {
		this.decorators.put(elementName, dec);
	}

	/**
	 * Subclasses can call this to register the supplied {@link BeanDefinitionDecorator} to
	 * handle the specified attribute. The attribute name is the local (non-namespace qualified)
	 * name.
	 */
	protected final void registerBeanDefinitionDecoratorForAttribute(String attrName, BeanDefinitionDecorator dec) {
		this.attributeDecorators.put(attrName, dec);
	}

}
